package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import server.component.Context;
import server.component.Host;
import server.component.Mapper;
import server.component.Wrapper;
import server.loader.MyClassLoader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**定义socket监听的端口号*/
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }


    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        // 加载解析相关的配置，web.xml

        loadServletByServer();
        //loadServlet();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );





        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        /*while(true) {
            Socket socket = serverSocket.accept();
            // 有了socket，接收到请求，获取输出流
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/


        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());
            socket.close();

        }*/


        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }

            socket.close();

        }
*/

        /*
            多线程改造（不使用线程池）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
            requestProcessor.start();
        }*/

        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while(true) {

            Socket socket = serverSocket.accept();

            RequestProcessor2 requestProcessor = new RequestProcessor2(socket,mapper);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }

    }
    public static List<String> getFiles(String path) {
        List<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(tempList[i].toString());
                //文件名，不包含路径
                //String fileName = tempList[i].getName();
            }
            if (tempList[i].isDirectory()) {
                //这里就不递归了，
            }
        }
        return files;
    }

    private Map<String,HttpServlet> servletMap = new HashMap<String,HttpServlet>();
    private Mapper mapper = new Mapper();

    private void loadServletByServer() {
        //自定义一个类加载器，可以指定需要读取的类的地址
        MyClassLoader myClassLoader = new MyClassLoader();
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            //获取所有service，目前只有一个
            List<Element> service = rootElement.selectNodes("//service");
            for (int i = 0; i < service.size(); i++) {
                Element element =  service.get(i);
                //解析连接器，得到MiniCat监听的是端口8080
                Element connector = (Element) element.selectSingleNode("Connector");
                String port = connector.attributeValue("port");
                //解析Engine和Host，得到请求的主机以及所有app存放的地址
                Element engine = (Element) element.selectSingleNode("Engine");
                Element hostEle = (Element) engine.selectSingleNode("Host");
                String hostName = hostEle.attributeValue("name");
                String hostAppBase = hostEle.attributeValue("appBase");

                //逐步构建各个组件
                Map<String,Context> contextMap = new HashMap<>();

                //进入指定的存放app的文件
                File file = new File(hostAppBase);
                File[] appList = file.listFiles();
                for (File appFile : appList) {
                    if (appFile.isDirectory()){
                        //文件夹名就是app名：demo1，demo2
                        String appFileName = appFile.getName();
                        Context context = new Context();
                        //找出app项目下的web.xml配置文件
                        File web_xml = appFile.listFiles(new FileFilter() {
                            @Override
                            public boolean accept(File file) {
                                return file.getName().endsWith(".xml");
                            }
                        })[0];

                        //构建wrapperMap
                        Map<String,Wrapper> wrapperMap = new HashMap<>();
                        //解析项目下的web.xml , 得到 路径和对应的servlet类
                        Map<String, String> urlPattern_servletClass = loadServletWebXml(web_xml.getAbsolutePath());
                        urlPattern_servletClass.forEach((p,c)->{
                            try {
                                // appWeb根路径 + app自己的路径 + web.xml中指定的servlet类路径
                                Class<?> aClass = myClassLoader.findClass(hostAppBase + "/" + appFileName + "/" + c);
                                Servlet servlet = (Servlet)aClass.newInstance();
                                //将servlet类加载进来，并封装到Wrapper中，以路径为key，存到wrapperMap中
                                wrapperMap.put(p,new Wrapper(servlet));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                        //完成context的封装
                        context.setWrapperMap(wrapperMap);
                        //已项目app为key，将整个context封装起来
                        contextMap.put(appFileName,context);
                    }
                }

                //最后构建host
                Host host = new Host();
                host.setContextMap(contextMap);
                Map<String,Host> hostMap = new HashMap<>();
                hostMap.put(hostName+":"+port,host);
                mapper.setHostMap(hostMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Map<String,String> loadServletWebXml(String webXmlPath) throws FileNotFoundException {
        Map<String,String> servletPath = new HashMap<>();
        File webXml = new File(webXmlPath);
        InputStream resourceAsStream = new FileInputStream(webXml);
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
                servletClass = servletClass.replace(".","/");


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletPath.put(urlPattern, servletClass);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return servletPath;
    }

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());

            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }


    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
